/*
 * @Author: earl 
 * @Date: 2018-12-10 16:36:51 
 * @Last Modified by: earl
 * @Last Modified time: 2018-12-10 17:14:11
 * @Describe:  post 请求获取参数
 */

 const Koa = require('Koa')
 const app = new Koa()

 app.use( async (ctx)=>{
   if( ctx.url === '/' && ctx.method === 'GET' ){
     // 当GET请求时返回表单页面
     let html = `
     <h1>koa2 request post demo</h1>
     <form method="POST" action="/">
       <p>userName</p>
       <input name="userName" /><br/>
       <p>nickName</p>
       <input name="nickName" /><br/>
       <p>email</p>
       <input name="email" /><br/>
       <button type="submit">submit</button>
     </form>
     `
     ctx.body = html
   } else if( ctx.url === '/' && ctx.method === 'POST' ){
      // 当POST请求的时候，解析POST表单里的数据，并显示出来
      let postData = await parsePostData( ctx )
      ctx.body = postData
   }else{
     // 其他请求显示404
     ctx.body = '<h1> 404!!!</h1>'
   }
 })

 // 解析上下文里的node原生请求的POST参数
function parsePostData( ctx ){
    return new Promise((resolve, reject) => {
      try{
        let postdata = ''
        ctx.req.addListener('data', (data) => {
          postdata += data
        })
        ctx.req.addListener('end', function(){
          let postData = parseQueryStr( postdata )
          resolve( postData )
        })
      }catch ( err ) {
          reject(err)
      } 
    })
} 

// 将POST请求参数解析到json参数
function parseQueryStr( queryStr ){
  let queryData = {}
  let queryStrList = queryStr.split('&')
  for( let [ index, queryStr ] of queryStrList.entries()){ // 该对象包含数组中每个索引的键/值对
    let itemList = queryStr.split('=')
    queryData[ itemList[0] ] = decodeURIComponent( itemList[1] )
  }
  return queryData
}

app.listen(3000, ()=>{
  console.log('[demo] request post is starting at port 3000')
})
